import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  Dimensions,
  Platform,
} from 'react-native';
import StepIndicator from 'react-native-step-indicator';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as orderActionCreator from '../../actions/order-actions';
import {connectActionSheet} from '@expo/react-native-action-sheet';
import ThemeStyles from '../../styles';
import {
  formatDate,
  getRealSize,
  SelectionSummary,
  Touchable,
} from '../../utils';
import {OrderState, OrderStateName} from '../../reducers/order-list';
import {I18n} from '../../reducers/intl';
import {Gender} from '../../reducers/order-form';
import _ from 'lodash';
import Separator from '../../components/separator';
import {BottomSheetModal, BottomSheetModalProvider} from '@gorhom/bottom-sheet';
import {Calendar} from 'react-native-calendars';
import FileUpload, {UploadState} from '../../components/file-upload';
import config from '../../../config.json';
import {UserType} from '../../reducers/user';
import Button from '../../components/button';
import ConfirmDialog, {DialogMode} from '../../components/confirm-dialog';
import IconFont from '../../resource/iconfont';
import {v4 as uuid} from 'uuid';

const StepStyles = {
  stepIndicatorSize: getRealSize(24), // 状态大小
  currentStepIndicatorSize: getRealSize(28), // 当前状态大小
  separatorStrokeWidth: getRealSize(24), // 进度条宽度
  currentStepStrokeWidth: getRealSize(2), // 当前状态边线宽度
  stepStrokeCurrentColor: ThemeStyles.Color.primary.color, //当前状态边线色
  stepStrokeWidth: getRealSize(2), // 状态边线宽度
  stepStrokeFinishedColor: ThemeStyles.Color.primary.color, // 已经完成的状态边线
  stepStrokeUnFinishedColor: '#c6c6c6', //未完成的状态边线色
  separatorFinishedColor: '#d7eaff', // 已经完成进度条色
  separatorUnFinishedColor: '#f7f7f7', // 未完成进度条色
  stepIndicatorFinishedColor: ThemeStyles.Color.primary.color, //已经完成的状态填充色
  stepIndicatorUnFinishedColor: '#fff', //未完成的状态填充色
  stepIndicatorCurrentColor: '#fff', // 当前状态里的填充色
  stepIndicatorLabelFontSize: getRealSize(12), // 非当前状态中的字体大小
  currentStepIndicatorLabelFontSize: getRealSize(12), // 当前状态中的字体大小
  stepIndicatorLabelCurrentColor: ThemeStyles.Color.primary.color, // 当前状态字体色
  stepIndicatorLabelFinishedColor: '#fff', //已经完成状态字体的色
  stepIndicatorLabelUnFinishedColor: '#c6c6c6', //未完成状态字体色
  labelColor: '#c6c6c6', // 状态字体色
  labelSize: getRealSize(10), // 状态字体大小
  currentStepLabelColor: ThemeStyles.Color.primary.color, //当前字体大小
};

const steps = [
  OrderState.ORDERING,
  OrderState.CONFIRMEN,
  OrderState.DELIVERY,
  OrderState.RECEIVED,
  OrderState.PAID,
  OrderState.ASSURE,
  OrderState.PRAISED,
];

const snapPoints = [320];

class OrderInfoScreen extends React.Component {
  static navigationOptions = () => ({
    headerBackTitleStyle: Platform.OS === 'ios' && {
      height: 0,
      width: 0,
    },
    title: I18n.t('page.title.orderInfo'),
  });

  state = {
    sheetIndex: 0,
  };

  onChangeFile = file => {
    const {
      order: {images = []},
      orderActions,
    } = this.props;
    const files = [...images, file];
    orderActions.update({images: files});
  };

  onProgress = (jobId, percentage) => {
    const {
      order: {images = []},
      orderActions,
    } = this.props;
    const files = images.map(file =>
      file.jobId === jobId
        ? {
            ...file,
            rate: Number(percentage / 100).toFixed(2),
            state: UploadState.UPLOADING,
          }
        : file,
    );
    orderActions.update({images: files});
  };

  onUploadSuccess = (result) => {
    const {order, orderActions} = this.props;
    const images = _.get(order, 'images', []);
    images.push(result);
    orderActions.update({images: [...images]});
    orderActions.updateOrderImages(order.id, [...images]);
  };

  onConfirmOrder = field => {
    const {navigation, order} = this.props;
    if (field === 'comment') {
      return navigation.navigate('OrderComment', {orderId: order.id});
    }
    if (field === 'confirm') {
      this.BottomSheet.present();
      const busyDates = _.get(order, 'seller.busy_dates', []);
      const dates = {};
      busyDates.forEach(o => {
        dates[o.date] = {disabled: true, disableTouchEvent: true};
      });
      this.setState({
        field,
        visible: false,
        id: order.id,
        dates,
      });
      return;
    }
    this.setState({
      field,
      visible: true,
      id: order.id,
    });
  };

  onChangeOrder = async () => {
    const {orderActions, order} = this.props;
    const {field, id} = this.state;
    await orderActions[field](id);
    orderActions.loadOrder(order.id);
  };

  renderActions = () => {
    const {order, user} = this.props;
    const userId = user.id;
    const userType = user.type;
    let role = '';
    if ([UserType.provider, UserType.technician].includes(userType)) {
      role = 'seller';
    } else {
      role = 'buyer';
    }
    const roleId = _.get(order, `${role}.id`, '');
    const selfOrder = roleId === userId;
    const disabled = order.cancelled || order.refused;
    const actions = [];

    if (
      [UserType.technician, UserType.provider].includes(userType) &&
      order.state === OrderState.ORDERING &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          key={uuid()}
          label={I18n.t('order.action.refuse')}
          style={Styles.btn}
          size="middle"
          type="ghost"
          onPress={() => this.onConfirmOrder('refuse')}
        />,
      );
      actions.push(
        <Button
          key={uuid()}
          style={Styles.btn}
          label={I18n.t('order.action.confirm')}
          type="ghost"
          onPress={() => this.onConfirmOrder('confirm')}
        />,
      );
    }

    if (
      [UserType.technician, UserType.provider].includes(userType) &&
      order.state === OrderState.CONFIRMEN &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          key={uuid()}
          style={Styles.btn}
          label={I18n.t('order.action.deliver')}
          type="ghost"
          onPress={() => this.onConfirmOrder('deliver')}
        />,
      );
    }

    if (
      [UserType.dentist, UserType.clinic].includes(userType) &&
      order.state === OrderState.ORDERING &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          key={uuid()}
          style={Styles.btn}
          label={I18n.t('order.action.cancel')}
          type="ghost"
          onPress={() => this.onConfirmOrder('cancel')}
        />,
      );
    }
    if (
      [UserType.dentist, UserType.clinic].includes(userType) &&
      order.state === OrderState.DELIVERY &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          key={uuid()}
          style={Styles.btn}
          label={I18n.t('order.action.receive')}
          type="ghost"
          onPress={() => this.onConfirmOrder('receive')}
        />,
      );
    }

    if (
      [UserType.dentist, UserType.clinic].includes(userType) &&
      order.state === OrderState.RECEIVED &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          key={uuid()}
          style={Styles.btn}
          label={I18n.t('order.action.paid')}
          type="ghost"
          onPress={() => this.onConfirmOrder('paid')}
        />,
      );
    }

    if (
      [UserType.technician, UserType.provider].includes(userType) &&
      order.state === OrderState.PAID &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          key={uuid()}
          style={Styles.btn}
          label={I18n.t('order.action.assure')}
          type="ghost"
          onPress={() => this.onConfirmOrder('assure')}
        />,
      );
    }

    if (
      [UserType.dentist, UserType.clinic].includes(userType) &&
      order.state === OrderState.ASSURE &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          key={uuid()}
          style={Styles.btn}
          label={I18n.t('order.action.comment')}
          type="ghost"
          onPress={() => this.onConfirmOrder('comment')}
        />,
      );
    }

    if (actions.length) {
      return <View style={Styles.action}>{actions}</View>;
    }
    return null;
  };

  render() {
    const {order, selections, token, user, orderActions, minDate} = this.props;
    order.stat = order.state;
    if (order.cancelled) {
      order.stat = OrderState.CANCELLED;
    } else if (order.refused) {
      order.stat = OrderState.REFUSED;
    }
    const userId = user.id;
    const userType = user.type;
    const position = steps.indexOf(order.state);
    let role = '';
    if ([UserType.provider, UserType.technician].includes(userType)) {
      role = 'seller';
    } else {
      role = 'buyer';
    }
    const roleId = _.get(order, `${role}.id`, '');
    const selfOrder = roleId === userId;
    // console.log(order.buyer.owner_info[0].clinic_name);
    // console.log(order.seller);
    return (
      <View>
        <BottomSheetModalProvider>
          <ScrollView>
            <ScrollView horizontal showsHorizontalScrollIndicator={false}>
              <View style={Styles.step}>
                <StepIndicator
                  customStyles={StepStyles}
                  currentPosition={position}
                  labels={steps.map(name => I18n.t(OrderStateName[name]))}
                  stepCount={steps.length}
                />
              </View>
            </ScrollView>
            <OrderCard {...order} />
            <PatientCard {...order} />
            <InfoCard {...order} options={selections} />
            <Separator />
            {[UserType.clinic, UserType.dentist].includes(user.type) && (
              <FileList
                {...order}
                disabled={
                  [UserType.technician, UserType.provider].includes(
                    user.type,
                  ) ||
                  !selfOrder ||
                  order.cancelled ||
                  order.refused ||
                  [OrderState.PRAISED].includes(order.state)
                }
                token={token.access}
                // onChangeFile={this.onChangeFile}
                // onProgress={this.onProgress}
                onUploadSuccess={this.onUploadSuccess}
              />
            )}
            <View style={{height: getRealSize(88)}} />
          </ScrollView>
          {this.renderActions()}
          <ConfirmDialog
            okLabel={I18n.t(`order.action.${this.state.field}`)}
            visible={this.state.visible}
            title={I18n.t(`order.action.${this.state.field}`)}
            content={I18n.t(`order.action.${this.state.field}`)}
            cancelLabel={I18n.t('button.close')}
            onConfirm={this.onChangeOrder}
            mode={DialogMode.confirm}
            onClose={() => this.setState({visible: false})}
          />
          <BottomSheetModal
            ref={ref => {
              this.BottomSheet = ref;
            }}
            index={0}
            handleComponent={() => (
              <SheetHead onClose={() => this.BottomSheet.close()} />
            )}
            snapPoints={snapPoints}>
            <Calendar
              markedDates={this.state.dates}
              horizontal={true}
              pagingEnabled={true}
              pastScrollRange={0}
              futureScrollRange={3}
              onDayPress={async day => {
                await orderActions.confirm(this.state.id, day.dateString);
                orderActions.loadOrder(this.state.id);
                this.BottomSheet.dismiss();
              }}
              minDate={minDate}
            />
          </BottomSheetModal>
        </BottomSheetModalProvider>
      </View>
    );
  }
}

const SheetHead = props => (
  <View style={Styles.sheetHead}>
    <View style={{width: 72}} />
    <IconFont name="molarzhedie" size={18} color="#DCDCDC" />
    <Touchable onPress={() => props.onClose()}>
      <View style={{width: 72}}>
        <Text style={Styles.headerLabel}>{I18n.t('button.close')}</Text>
      </View>
    </Touchable>
  </View>
);

const FileList = props => {
  const files = _.get(props, 'images', []);
  return (
    <View style={Styles.box}>
      <View style={Styles.head}>
        <Text style={[Styles.title, ThemeStyles.Color.primary, {flex: 1}]}>
          {I18n.t('form.label.file.name')}
        </Text>
        <Text
          style={[
            Styles.title,
            ThemeStyles.Color.primary,
            {flex: 1, textAlign: 'right'},
          ]}>
          {I18n.t('form.label.file.desc', {length: files.length})}
        </Text>
      </View>
      <FileUpload
        disabled={props.disabled}
        token={props.token}
        uploadUrl={`${config.httpClient.host}/web/planimage/new`}
        files={files}
        onSuccess={props.onUploadSuccess}
      />
    </View>
  );
};

const InfoCard = props => (
  <View style={Styles.box}>
    <View style={Styles.row}>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.dentist')}</Text>
        <Text style={Styles.value} numberOfLines={1}>
          {_.get(props, 'buyer.clinic_name', '')}
        </Text>
      </View>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.clinic')}</Text>
        <Text style={Styles.value} numberOfLines={1}>
          {_.get(props, 'buyer.owner_info[0].clinic_name', '')}
        </Text>
      </View>
    </View>
    <View style={Styles.innerRow}>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.technician')}</Text>
        <Text style={Styles.value} numberOfLines={1}>
          {_.get(props, 'seller.vendor_name', '')}
        </Text>
      </View>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.provider')}</Text>
        <Text style={Styles.value} numberOfLines={1}>
          {_.get(props, 'seller.owner_info.vendor_name', '')}
        </Text>
      </View>
    </View>
    <View style={Styles.extra}>
      <Text style={Styles.title}>{I18n.t('order.props.selections')}</Text>
      <Text style={Styles.desc} numberOfLines={1}>
        {SelectionSummary(props.selections || [], props.options || [])}
      </Text>
    </View>
  </View>
);

const OrderCard = props => (
  <View style={Styles.box}>
    <View style={Styles.row}>
        <View style={Styles.block}>
          <Text style={Styles.title}>{I18n.t('order.props.no')}</Text>
          <Text style={Styles.value} numberOfLines={1}>
            {props.order_no}
          </Text>
        </View>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.state')}</Text>
        <Text style={Styles.value} numberOfLines={1}>
          {I18n.t(OrderStateName[props.stat])}
        </Text>
      </View>
    </View>
    <View style={Styles.innerRow}>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.created')}</Text>
        <Text style={Styles.value} numberOfLines={1}>
          {formatDate(props.created)}
        </Text>
      </View>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.deliveryDay')}</Text>
        <Text style={Styles.value} numberOfLines={1}>
          {formatDate(props.delivery_day)}
        </Text>
      </View>
    </View>
  </View>
);

const PatientCard = props => (
  <View style={Styles.box}>
    <View style={Styles.row}>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.patient.name')}</Text>
        <Text style={Styles.value} numberOfLines={1}>
          {props.patient_name}
        </Text>
      </View>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.patient.gender')}</Text>
        <Text style={Styles.value}>
          {props.patient_gender && Gender[props.patient_gender].label}
        </Text>
      </View>
    </View>
    <View style={Styles.innerRow}>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.patient.age')}</Text>
        <Text style={Styles.value}>{props.patient_age}</Text>
      </View>
      <View style={Styles.block}>
        <Text style={Styles.title}>{I18n.t('order.props.patient.from')}</Text>
        <Text style={Styles.value} numberOfLines={1}>
          {props.owners}
        </Text>
      </View>
    </View>
  </View>
);

const mapStateToProps = state => ({
  appState: state.appState,
  user: state.user,
  order: state.order,
  token: state.token,
  selections: state.constant.selections,
  minDate: formatDate(),
});

const mapDispatchToProps = dispatch => ({
  orderActions: bindActionCreators(orderActionCreator, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(connectActionSheet(OrderInfoScreen));

const Styles = StyleSheet.create({
  container: {
    ...ThemeStyles.Color.background.white,
    paddingHorizontal: getRealSize(15),
  },
  step: {
    width: getRealSize(688),
    paddingHorizontal: getRealSize(15),
    paddingVertical: getRealSize(15),
  },
  box: {
    marginHorizontal: getRealSize(15),
    padding: getRealSize(20),
    backgroundColor: '#f7f7f7',
    marginTop: getRealSize(15),
    borderRadius: getRealSize(4),
  },
  extra: {
    borderTopColor: '#999',
    borderTopWidth: StyleSheet.hairlineWidth,
    paddingTop: getRealSize(12),
    marginTop: getRealSize(12),
  },
  head: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: getRealSize(8),
  },
  desc: {
    fontSize: getRealSize(12),
    color: ThemeStyles.Color.text.tintGray.color,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  innerRow: {
    marginTop: getRealSize(20),
    flexDirection: 'row',
    alignItems: 'center',
  },
  action: {
    width: Dimensions.get('screen').width,
    position: 'absolute',
    bottom: 0,
    backgroundColor: '#fff',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-end',
    paddingVertical: getRealSize(4),
    paddingHorizontal: getRealSize(12),
  },
  block: {
    flex: 1,
    // marginRight: getRealSize(12),
  },
  title: {
    fontSize: getRealSize(12),
    fontWeight: '400',
    color: '#757575',
  },
  value: {
    marginTop: getRealSize(12),
    fontSize: getRealSize(14),
    fontWeight: 'bold',
    color: '#333',
    flex: 1,
  },
  fileContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  fileLabel: {
    flex: 1,
    color: '#333',
    marginRight: getRealSize(12),
  },
  file: {
    width: getRealSize(64),
    height: getRealSize(64),
  },
  sheetContainer: {
    borderTopColor: ThemeStyles.Color.line.color,
    borderTopWidth: StyleSheet.hairlineWidth,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 12,
    },
    shadowOpacity: 0.58,
    shadowRadius: 16.0,

    elevation: 24,
  },
  btn: {
    marginLeft: getRealSize(8),
  },
});
